package com.itlong.cloud.controller.property;

import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.project.property.IPropertyBuildInfoServiceClient;
import com.itlong.cloud.project.property.IPropertyRoomInfoServiceClient;
import com.itlong.cloud.project.property.IPropertyUnitInfoServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * <desc>
 *      单元信息管理控制器
 * </desc>
 *
 * @createDate 2017-09-21
 */
@RestController
@RequestMapping("project/unitInfo")
public class PropertyUnitInfoController extends BaseController {

    private final IPropertyRoomInfoServiceClient iPropertyRoomInfoServiceClient; //房屋信息房屋接口协议提供对象

    private final IPropertyUnitInfoServiceClient iPropertyUnitInfoServiceClient;   //单元信息服务接口协议提供对象.

    private final IPropertyBuildInfoServiceClient iPropertyBuildInfoServiceClient; //楼栋信息接口协议提供对象

    private final IPropertyEquipServiceClient iPropertyEquipServiceClient; //设备信息接口协议提供对象

    @Autowired
    public PropertyUnitInfoController(IPropertyRoomInfoServiceClient iPropertyRoomInfoServiceClient, IPropertyUnitInfoServiceClient iPropertyUnitInfoServiceClient, IPropertyBuildInfoServiceClient iPropertyBuildInfoServiceClient, IPropertyEquipServiceClient iPropertyEquipServiceClient) {
        this.iPropertyRoomInfoServiceClient = iPropertyRoomInfoServiceClient;
        this.iPropertyUnitInfoServiceClient = iPropertyUnitInfoServiceClient;
        this.iPropertyBuildInfoServiceClient = iPropertyBuildInfoServiceClient;
        this.iPropertyEquipServiceClient = iPropertyEquipServiceClient;
    }


    /**
     * <desc>
     *      保存单个单元信息
     * </desc>
     *
     * @param propertyProjectSaveUnitInfoDTO 添加单元信息数据传输对象
     * @return MessageVO 标准格式化响应结果
     * @author LouisLewis
     * @createDate 2017-09-26
     */
    @LoggerInfo(operateDesc = LogDescConstant.SAVE_UNITINFO_LOG_DESC)
    @RequestMapping(path = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Object saveUnitInfo(PropertyProjectSaveUnitInfoDTO propertyProjectSaveUnitInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectSaveUnitInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectSaveUnitInfoDTO.class, request);
            //判断参数合法性
            if ((null == propertyProjectSaveUnitInfoDTO)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //单元名称不能为空
            if (StringUtils.isBlank(propertyProjectSaveUnitInfoDTO.getUnitName())) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NAME_EMPTY_ERR.getErrorCode());
            }

            //单元名称过长
            if (propertyProjectSaveUnitInfoDTO.getUnitName().length() > PlatformConstants.MAX_UNIT_NAME_LENGTH ){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NAME_LENGTH_ERR.getErrorCode());
            }

            //项目编号不能为空
            if (StringUtils.isBlank(propertyProjectSaveUnitInfoDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }

            // 单元组号不能为空
            if (StringUtils.isBlank(propertyProjectSaveUnitInfoDTO.getUnitGroupNum())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //楼栋ID不能为空
            if (StringUtils.isBlank(propertyProjectSaveUnitInfoDTO.getBuildId())) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_ID_EMPTY_ERR.getErrorCode());
            }

            String unitNum = propertyProjectSaveUnitInfoDTO.getUnitNum();
            // 单元编号不能为空
            if (StringUtils.isBlank(unitNum)){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NUM_EMPTY_ERR.getErrorCode());
            }
            // 判断单元编号的合法性
            int intUnitNum = StringHandlerUtil.strToIntDef(unitNum, 0);
            if (!NumberHandlerUtil.isInRange(intUnitNum,PlatformConstants.MIN_UNIT_NUM,PlatformConstants.MAX_UNIT_NUM)){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NUM_INVALID_ERR.getErrorCode());
            }
            // 同一楼栋下单元编号唯一
            unitNum = NumberHandlerUtil.numFormatToString(intUnitNum,2);
            PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO = new PropertyProjectGetUnitInfoDTO();
            propertyProjectGetUnitInfoDTO.setBuildId(propertyProjectSaveUnitInfoDTO.getBuildId());
            propertyProjectGetUnitInfoDTO.setUnitNum(unitNum);
            PropertyProjectUnitInfoVO oneUnitInfo = iPropertyUnitInfoServiceClient.getOneUnitInfo(propertyProjectGetUnitInfoDTO);
            if (oneUnitInfo != null){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NUM_EXIST_ERR.getErrorCode());
            }
            propertyProjectSaveUnitInfoDTO.setUnitNum(unitNum);

            //楼栋单元代号是否格式非法
            String unitAlias = propertyProjectSaveUnitInfoDTO.getUnitAlias();
            if (StringUtils.isNotBlank(unitAlias)) {
                int intUnitAlias = StringHandlerUtil.strToIntDef(unitAlias, 0);
                if ((!NumberHandlerUtil.isInRange(intUnitAlias, PlatformConstants.MIN_UNIT_ALIAS,
                        PlatformConstants.MAX_UNIT_ALIAS)
                        || (intUnitAlias == PlatformConstants.INVALID_ALIAS))) {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_ALIAS_INVALID_ERR.getErrorCode());
                }

                //自动消去楼栋单元代号可能的前置0，如 "0301"->"301", "00301"->"301"
                unitAlias = unitAlias.replaceAll("^(0+)", "");

                //楼栋单元代号在当前项目内不允许重复
                if (null != getUnitInfoByUnitAlias(unitAlias,
                        propertyProjectSaveUnitInfoDTO.getProjectId())) {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_ALIAS_REPEAT_ERR.getErrorCode());
                }

                propertyProjectSaveUnitInfoDTO.setUnitAlias(unitAlias);
            }

            //单元名称在当前单元内不允许重复
            if (null != getUnitInfoByUnitName(propertyProjectSaveUnitInfoDTO.getUnitName(),
                    propertyProjectSaveUnitInfoDTO.getBuildId())) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NAME_REPEAT_ERR.getErrorCode());
            }

            //所属楼栋不存在，则不允许添加
            PropertyProjectGetBuildInfoDTO propertyProjectGetBuildInfoDTO = new PropertyProjectGetBuildInfoDTO();
            propertyProjectGetBuildInfoDTO.setBuildId( propertyProjectSaveUnitInfoDTO.getBuildId());
            PropertyProjectBuildInfoVO propertyProjectBuildInfoVO = iPropertyBuildInfoServiceClient.getOneBuildInfo(propertyProjectGetBuildInfoDTO);
            if (null == propertyProjectBuildInfoVO){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_INFO_NOT_EXISTS_ERR.getErrorCode());
            }

            //当前楼栋下的单元数量已达上限
            if (propertyProjectBuildInfoVO.getUnitCount() >= PlatformConstants.MAX_UNIT_NUM){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_IMPORT_TOO_MANY_UNIT_ERR.getErrorCode());
            }

//            String newAvailableUnitNum = iPropertyUnitInfoServiceClient.getMinAvailableUnitNum(propertyProjectSaveUnitInfoDTO.getBuildId());
//            propertyProjectSaveUnitInfoDTO.setUnitNum(newAvailableUnitNum);
            //若单元代号不存在，则自动生成
            if (StringUtils.isBlank(unitAlias)){
                PropertyProjectGetMinAvaliableUnitAliasDTO getMinAvaliableUnitAliasDTO = new PropertyProjectGetMinAvaliableUnitAliasDTO();
                getMinAvaliableUnitAliasDTO.setProjectId(propertyProjectSaveUnitInfoDTO.getProjectId());
                getMinAvaliableUnitAliasDTO.setUnitNum(unitNum);
                getMinAvaliableUnitAliasDTO.setBuildNum(propertyProjectBuildInfoVO.getBuildNum());
                getMinAvaliableUnitAliasDTO.setBuildId(propertyProjectBuildInfoVO.getBuildId());
                getMinAvaliableUnitAliasDTO.setUnitCount(propertyProjectBuildInfoVO.getUnitCount());
                unitAlias = iPropertyUnitInfoServiceClient.getMinAvaliableUnitAlias(getMinAvaliableUnitAliasDTO);
                propertyProjectSaveUnitInfoDTO.setUnitAlias(unitAlias);
            }

            //保存单元信息
            iPropertyUnitInfoServiceClient.saveUnitInfo(propertyProjectSaveUnitInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());


        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】保存单元信息失败", e);
        }
    }

    /**
     * <desc>
     *     指定楼栋的最小可用单元编号(UnitNum)
     * </desc>
     *
     * @param buildId 楼栋id
     * @return 最小可用单元编号
     * @author wangzhi
     * @createDate 2018/05/29
     */
    @PostMapping(path = "/getMinAvailableUnitNum")
    @ResponseBody
    public Object getMinAvailableUnitNumByBuildId(String buildId){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            buildId = request.getAttribute("buildId") == null ? null : request.getAttribute("buildId").toString();
            // 楼栋id不能为空
            if (StringUtils.isBlank(buildId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String unitNum = iPropertyUnitInfoServiceClient.getMinAvailableUnitNum(buildId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),(Object)unitNum);
        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】获取指定楼栋的最小可用单元编号失败", e);
        }
    }

    /**
     * <desc>
     *     获取最小可用的单元编号、代号、组号
     * </desc>
     *
     * @param getMinAvaliableUnitAliasDTO 查询对象
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/08/21
     */
    @RequestMapping("getMinAvailableUnitData")
    @ResponseBody
    public Object getMinAvailableUnitData(PropertyProjectGetMinAvaliableUnitAliasDTO getMinAvaliableUnitAliasDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            getMinAvaliableUnitAliasDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetMinAvaliableUnitAliasDTO.class, request);
            PropertyUnitMinAvailAbleDataVO propertyUnitMinAvailAbleDataVO = new PropertyUnitMinAvailAbleDataVO();

            if ((null == getMinAvaliableUnitAliasDTO) ||
                    (StringUtils.isBlank(getMinAvaliableUnitAliasDTO.getBuildId()))
                    ||(StringUtils.isBlank(getMinAvaliableUnitAliasDTO.getProjectId()))){
                return  new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyProjectGetBuildInfoDTO buildInfoDTO = new PropertyProjectGetBuildInfoDTO();
            buildInfoDTO.setProjectId(getMinAvaliableUnitAliasDTO.getProjectId());
            buildInfoDTO.setBuildId(getMinAvaliableUnitAliasDTO.getBuildId());
            PropertyProjectBuildInfoVO buildInfoVO = iPropertyBuildInfoServiceClient.getOneBuildInfo(buildInfoDTO);
            if (null == buildInfoVO){
                return  new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_INFO_NOT_EXISTS_ERR.getErrorCode());
            }
            // getMinAvaliableUnitAliasDTO.setUnitNum(propertyProjectUpdateUnitInfoDTO.getUnitNum());
            getMinAvaliableUnitAliasDTO.setUnitCount(buildInfoVO.getUnitCount());
            String unitNum = iPropertyUnitInfoServiceClient.getMinAvailableUnitNum(getMinAvaliableUnitAliasDTO.getBuildId());
            getMinAvaliableUnitAliasDTO.setUnitNum(unitNum);
            getMinAvaliableUnitAliasDTO.setBuildNum(buildInfoVO.getBuildNum());
            String unitAlias = iPropertyUnitInfoServiceClient.getMinAvaliableUnitAlias(getMinAvaliableUnitAliasDTO);
            propertyUnitMinAvailAbleDataVO.setUnitAlias(unitAlias);
            propertyUnitMinAvailAbleDataVO.setUnitNum(unitNum);

            String unitGroupNum = iPropertyUnitInfoServiceClient.getMinAvailableUnitGroupNum(getMinAvaliableUnitAliasDTO.getProjectId());
            propertyUnitMinAvailAbleDataVO.setUnitGroupNum(unitGroupNum);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyUnitMinAvailAbleDataVO);
        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】获取最小可用的单元编号、代号、组号失败", e);
        }
    }

    /**
     * <desc>
     *      一次性接口，初始化所有单元组号
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/08/21
     */
    @RequestMapping("initializeUnitGroupNum")
    @ResponseBody
    public Object initializeUnitGroupNum(){
        try {
            iPropertyUnitInfoServiceClient.initializeUnitGroupNum();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】一次性接口初始化所有单元组号失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目动态密码验证方式
     * </desc>
     *
     * @param projectId 项目id
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/08/21
     */
    @RequestMapping("getProjectOtpOnline")
    @ResponseBody
    public Object getProjectOtpOnline(String projectId){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            if (StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            Integer otpOnline = iPropertyUnitInfoServiceClient.getProjectOtpOnline(projectId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),otpOnline);
        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】获取项目动态密码验证方式失败", e);
        }
    }

    /**
     * <desc>
     *      修改单元信息【根据单元Id（UnitId）】
     * </desc>
     *
     * @param propertyProjectUpdateUnitInfoDTO 修改单元信息数据传输对象
     * @return MessageVO 标准格式化响应结果
     * @author LouisLewis
     * @createDate 2017-09-30
     */
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_UNITINFO_LOG_DESC)
    @RequestMapping(path = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateUnitInfo(PropertyProjectUpdateUnitInfoDTO propertyProjectUpdateUnitInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectUpdateUnitInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectUpdateUnitInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectUpdateUnitInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //单元ID不能为空
            if (StringUtils.isBlank(propertyProjectUpdateUnitInfoDTO.getUnitId())) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_ID_EMPTY_ERR.getErrorCode());
            }

            //单元信息是否仍然存在（可能已被其它地方删除），不存在则不允许更新
            PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO = new PropertyProjectGetUnitInfoDTO();
            propertyProjectGetUnitInfoDTO.setUnitId(propertyProjectUpdateUnitInfoDTO.getUnitId());
            PropertyProjectUnitInfoVO oldPropertyProjectUnitInfoVO = iPropertyUnitInfoServiceClient.getOneUnitInfo(propertyProjectGetUnitInfoDTO);
            if (oldPropertyProjectUnitInfoVO == null) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_INFO_NOT_EXISTS_ERR.getErrorCode());
            }

            //判定是否需要更新云对讲，若需更新，底层将进行RabbitMQ通知
            boolean needNotifyIntercom = (oldPropertyProjectUnitInfoVO.getRoomCount() > 0)
                    && (!StringHandlerUtil.compareStrWithOutEmpty(oldPropertyProjectUnitInfoVO.getUnitAlias(),propertyProjectUpdateUnitInfoDTO.getUnitAlias()));
            propertyProjectUpdateUnitInfoDTO.setNeedNotifyIntercom(needNotifyIntercom);

            //如需更新单元名称，则需对单元名称进行合法性检测
            String newUnitName = propertyProjectUpdateUnitInfoDTO.getUnitName();
            if (newUnitName != null) {
                //单元名称不能为空
                if (StringUtils.isBlank(newUnitName)) {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NAME_EMPTY_ERR.getErrorCode());
                }


                //单元名称过长
                if (newUnitName.length() > PlatformConstants.MAX_UNIT_NAME_LENGTH ){
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NAME_LENGTH_ERR.getErrorCode());
                }

                //若单元名称出现变更,检查新名称是否被占用
                if (!StringHandlerUtil.compareStrWithOutEmpty(oldPropertyProjectUnitInfoVO.getUnitName(), newUnitName)
                        && null != getUnitInfoByUnitName(newUnitName, oldPropertyProjectUnitInfoVO.getBuildId())) {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_NAME_REPEAT_ERR.getErrorCode());
                }
            }

            //如需更新楼栋单元代号，则需对楼栋单元代号进行合法性检测
            String newUnitAlias = propertyProjectUpdateUnitInfoDTO.getUnitAlias();
            if ((newUnitAlias != null) && (newUnitAlias.length() > 0)) {
                //楼栋单元代号是否格式非法
                int intUnitAlias = StringHandlerUtil.strToIntDef(newUnitAlias, 0);
                if ((!NumberHandlerUtil.isInRange(intUnitAlias, PlatformConstants.MIN_UNIT_ALIAS,
                        PlatformConstants.MAX_UNIT_ALIAS)
                        || (intUnitAlias == PlatformConstants.INVALID_ALIAS))) {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_ALIAS_INVALID_ERR.getErrorCode());
                }

                //自动消去楼栋单元代号可能的前置0，如 "0301"->"301", "00301"->"301"
                newUnitAlias = newUnitAlias.replaceAll("^(0+)", "");
                //若楼栋单元代号出现变更,检查新楼栋单元代号是否被占用
                if (!StringHandlerUtil.compareStrWithOutEmpty(oldPropertyProjectUnitInfoVO.getUnitAlias(),
                        newUnitAlias)) {
                    if (null != getUnitInfoByUnitAlias(newUnitAlias, propertyProjectUpdateUnitInfoDTO.getProjectId())) {
                        return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_ALIAS_REPEAT_ERR.getErrorCode());
                    }
                }
                propertyProjectUpdateUnitInfoDTO.setUnitAlias(newUnitAlias);
            }

            //若单元代号不存在，则自动生成
            if (StringUtils.isBlank(newUnitAlias)){

                //如果原有单元代号不为空，则优先使用原单元代号
                if (StringUtils.isNotBlank(oldPropertyProjectUnitInfoVO.getUnitAlias())){
                    newUnitAlias = oldPropertyProjectUnitInfoVO.getUnitAlias();
                } else {
                    //所属楼栋不存在，则不允许添加
                    PropertyProjectGetBuildInfoDTO propertyProjectGetBuildInfoDTO = new PropertyProjectGetBuildInfoDTO();
                    propertyProjectGetBuildInfoDTO.setBuildId( propertyProjectUpdateUnitInfoDTO.getBuildId());
                    PropertyProjectBuildInfoVO propertyProjectBuildInfoVO = iPropertyBuildInfoServiceClient.getOneBuildInfo(propertyProjectGetBuildInfoDTO);
                    if (null == propertyProjectBuildInfoVO){
                        return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_INFO_NOT_EXISTS_ERR.getErrorCode());
                    }

                    PropertyProjectGetMinAvaliableUnitAliasDTO getMinAvaliableUnitAliasDTO = new PropertyProjectGetMinAvaliableUnitAliasDTO();
                    getMinAvaliableUnitAliasDTO.setProjectId(propertyProjectUpdateUnitInfoDTO.getProjectId());
                    getMinAvaliableUnitAliasDTO.setUnitNum(propertyProjectUpdateUnitInfoDTO.getUnitNum());
                    getMinAvaliableUnitAliasDTO.setBuildId(propertyProjectBuildInfoVO.getBuildId());
                    getMinAvaliableUnitAliasDTO.setBuildNum(propertyProjectBuildInfoVO.getBuildNum());
                    getMinAvaliableUnitAliasDTO.setUnitCount(propertyProjectBuildInfoVO.getUnitCount());
                    newUnitAlias = iPropertyUnitInfoServiceClient.getMinAvaliableUnitAlias(getMinAvaliableUnitAliasDTO);
                }

                propertyProjectUpdateUnitInfoDTO.setUnitAlias(newUnitAlias);
            }
            //修改单元信息
            iPropertyUnitInfoServiceClient.updateUnitInfo(propertyProjectUpdateUnitInfoDTO);
            return new MessageVO(propertyProjectUpdateUnitInfoDTO.getUnitId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());


        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】修改单元信息失败", e);
        }
    }

    /**
     * <desc>
     *      根据条件逻辑删除单元信息
     * </desc>
     *
     * @param propertyProjectRemoveUnitInfoDTO 删除单元信息数据传输对象
     * @return MessageVO 标准格式化响应结果
     * @author LouisLewis
     * @createDate 2017-09-27
     */
    @LoggerInfo(operateDesc = LogDescConstant.DELETE_UNITINFO_LOG_DESC)
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object removeUnitInfo(PropertyProjectRemoveUnitInfoDTO propertyProjectRemoveUnitInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectRemoveUnitInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectRemoveUnitInfoDTO.class, request);
            //判断参数合法性（必须有楼栋ID或单元ID才允许进行删除）
            if ((null == propertyProjectRemoveUnitInfoDTO)
                    || ((StringUtils.isBlank(propertyProjectRemoveUnitInfoDTO.getUnitId()))
                    && (StringUtils.isBlank(propertyProjectRemoveUnitInfoDTO.getBuildId())))) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //楼栋或单元下存在房间，不允许删除
            if (checkHasRoomInBuildOrUnit(propertyProjectRemoveUnitInfoDTO.getBuildId(),
                    propertyProjectRemoveUnitInfoDTO.getUnitId())) {
                if (null != propertyProjectRemoveUnitInfoDTO.getUnitId()) {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_UNIT_HAS_ROOM_DELETE_ERR.getErrorCode());
                } else {
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_HAS_ROOM_DELETE_ERR.getErrorCode());
                }

            }

            //首先调用设备服务删除设备-地址关系，在设备服务实现层再通过RabbitMQ发送消息到项目服务上删除地址
            iPropertyEquipServiceClient.deleteAddress(propertyProjectRemoveUnitInfoDTO);

            return new MessageVO(propertyProjectRemoveUnitInfoDTO.getUnitId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());


        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】删除单元信息失败", e);
        }
    }

    /**
     * <desc>
     *      分页查询单元信息
     * </desc>
     *
     * @param propertyProjectGetUnitInfoDTO 分页查询楼栋信息数据传输对象
     * @return MessageVO 标准格式化响应结果
     * @author LouisLewis
     * @createDate 2017-09-25
     */
    @RequestMapping(path = "getPage", method = RequestMethod.POST)
    @ResponseBody
    public Object getPage(PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetUnitInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetUnitInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectGetUnitInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //项目编号不能为空
            if (StringUtils.isBlank(propertyProjectGetUnitInfoDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }

            Page<PropertyProjectUnitInfoVO> page = iPropertyUnitInfoServiceClient.getPage(propertyProjectGetUnitInfoDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】分页查询单元信息失败", e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *      分页查询指定楼栋下的单元简单信息（单元id ,单元名称）列表
     * </desc>
     *
     * @param propertyProjectGetUnitSimpleInfoDTO 查询单元简单信息（单元ID，单元名称）数据传输对象
     * @return MessageVO 标准格式化响应结果（含单元简单信息（单元id ,单元名称）列表）
     * @author LewisLouis
     * @createDate 2017-09-28
     */
    @RequestMapping(path = "/getPageSimpleList", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageUnitSimpleInfoList(PropertyProjectGetUnitSimpleInfoDTO propertyProjectGetUnitSimpleInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetUnitSimpleInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetUnitSimpleInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectGetUnitSimpleInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //楼栋编号不能为空
            if ((StringUtils.isBlank(propertyProjectGetUnitSimpleInfoDTO.getBuildId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_ID_EMPTY_ERR.getErrorCode());
            }
            //分页查询单元简单信息列表
            Page<PropertyProjectUnitSimpleInfoVO> page = iPropertyUnitInfoServiceClient.getPageUnitSimpleInfoList(propertyProjectGetUnitSimpleInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);


        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】分页查询单元简单信息列表失败", e);
        }
    }


    /**
     * <desc>
     *      分页查询指定楼栋下的单元简单扩展信息（单元id ,单元名称,单元下房间数量）列表
     * </desc>
     *
     * @param propertyProjectGetUnitSimpleInfoDTO 查询单元简单信息（单元ID，单元名称）数据传输对象
     * @return MessageVO 标准格式化响应结果（含单元简单扩展信息（单元id ,单元名称,单元下房间数量）列表）
     * @author LewisLouis
     * @createDate 2017-11-10
     */
    @RequestMapping(path = "/getPageSimpleListEx", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageUnitSimpleInfoExList(PropertyProjectGetUnitSimpleInfoDTO propertyProjectGetUnitSimpleInfoDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetUnitSimpleInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetUnitSimpleInfoDTO.class, request);
            //判断参数合法性
            if (null == propertyProjectGetUnitSimpleInfoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //楼栋编号不能为空
            if ((StringUtils.isBlank(propertyProjectGetUnitSimpleInfoDTO.getBuildId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_ID_EMPTY_ERR.getErrorCode());
            }
            //分页查询单元简单扩展信息列表
            Page<PropertyProjectUnitSimpleInfoExVO> page = iPropertyUnitInfoServiceClient.getPageUnitSimpleInfoExList(propertyProjectGetUnitSimpleInfoDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);


        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】分页查询单元简单扩展信息列表失败", e);
        }
    }
    /**
     * <desc>
     *      精确查询，获取单个单元信息
     * </desc>
     *
     * @param propertyProjectGetUnitInfoDTO 查询单元信息数据传输对象
     * @return MessageVO 标准格式化响应结果（含按创建时间降序排列，首个符合查询条件的单元信息）
     * @author LouisLewis
     * @createDate 2017-09-29
     */
    @RequestMapping(path = "getOne", method = RequestMethod.POST)
    @ResponseBody
    public Object getOne(PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyProjectGetUnitInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetUnitInfoDTO.class, request);
            if (StringUtils.isNotBlank(propertyProjectGetUnitInfoDTO.getUnitNum())){
                String unitNum = propertyProjectGetUnitInfoDTO.getUnitNum();
                unitNum = StringHandlerUtil.formatStrLen(unitNum,"0",2,false,false);
                propertyProjectGetUnitInfoDTO.setUnitNum(unitNum);
            }
            PropertyProjectUnitInfoVO propertyProjectUnitInfoVO = iPropertyUnitInfoServiceClient.getOneUnitInfo(propertyProjectGetUnitInfoDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), propertyProjectUnitInfoVO);
        } catch (Exception e) {
            throw new DataAccessException("【物业_项目_单元信息】精确查询单个单元信息失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取最小可用单元代号
     * </desc>
     *
     * @param getMinAvaliableUnitAliasDTO 获取最小可用单元代号查询对象
     * @return MessageVO 标准格式化响应结果
     * @author LouisLewis
     * @createDate 2018-01-15
     */
    @RequestMapping(path = "getMinAvaliableUnitAlias", method = RequestMethod.POST)
    @ResponseBody
    public Object getMinAvaliableUnitAlias(PropertyProjectGetMinAvaliableUnitAliasDTO getMinAvaliableUnitAliasDTO){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        getMinAvaliableUnitAliasDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyProjectGetMinAvaliableUnitAliasDTO.class, request);

        if ((null == getMinAvaliableUnitAliasDTO) ||
                (StringUtils.isBlank(getMinAvaliableUnitAliasDTO.getBuildId()))
                ||(StringUtils.isBlank(getMinAvaliableUnitAliasDTO.getProjectId()))){
            return  new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
        }
        PropertyProjectGetBuildInfoDTO buildInfoDTO = new PropertyProjectGetBuildInfoDTO();
        buildInfoDTO.setProjectId(getMinAvaliableUnitAliasDTO.getProjectId());
        buildInfoDTO.setBuildId(getMinAvaliableUnitAliasDTO.getBuildId());
        PropertyProjectBuildInfoVO buildInfoVO = iPropertyBuildInfoServiceClient.getOneBuildInfo(buildInfoDTO);
        if (null == buildInfoVO){
            return  new MessageVO(PropertyErrorCodeEnum.PROJECT_BUILD_INFO_NOT_EXISTS_ERR.getErrorCode());
        }
       // getMinAvaliableUnitAliasDTO.setUnitNum(propertyProjectUpdateUnitInfoDTO.getUnitNum());
        getMinAvaliableUnitAliasDTO.setUnitCount(buildInfoVO.getUnitCount());
        String unitNum = iPropertyUnitInfoServiceClient.getMinAvailableUnitNum(getMinAvaliableUnitAliasDTO.getBuildId());
        getMinAvaliableUnitAliasDTO.setUnitNum(unitNum);
        getMinAvaliableUnitAliasDTO.setBuildNum(buildInfoVO.getBuildNum());
        String unitAlias = iPropertyUnitInfoServiceClient.getMinAvaliableUnitAlias(getMinAvaliableUnitAliasDTO);
        return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),(Object)unitAlias);
    }

    /**
     * <desc>
     *      根据单元名称精确查询单元信息
     * </desc>
     *
     * @param unitName 单元名称
     * @return 单元信息
     * @author LewisLouis
     * @createDate 2017-10-18
     */
    private PropertyProjectUnitInfoVO getUnitInfoByUnitName(String unitName, String buildId) {
        PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO = new PropertyProjectGetUnitInfoDTO();
        propertyProjectGetUnitInfoDTO.setBuildId(buildId);
        propertyProjectGetUnitInfoDTO.setUnitName(unitName);
        return iPropertyUnitInfoServiceClient.getOneUnitInfo(propertyProjectGetUnitInfoDTO);
    }

    /**
     * <desc>
     *      根据楼栋单元代号精确查询单元信息
     * </desc>
     *
     * @param unitAlias 单元代号
     * @return 单元信息
     * @author LewisLouis
     * @createDate 2017-10-18
     */
    private PropertyProjectUnitInfoVO getUnitInfoByUnitAlias(String unitAlias, String projectId) {
        PropertyProjectGetUnitInfoDTO propertyProjectGetUnitInfoDTO = new PropertyProjectGetUnitInfoDTO();
        propertyProjectGetUnitInfoDTO.setProjectId(projectId);
        propertyProjectGetUnitInfoDTO.setUnitAlias(unitAlias);
        return iPropertyUnitInfoServiceClient.getOneUnitInfo(propertyProjectGetUnitInfoDTO);
    }


    /**
     * <desc>
     *      检查指定楼栋或单元下是否存在房间信息.
     * </desc>
     *
     * @param buildId 楼栋ID
     * @param unitId  单元ID
     * @return True：存在    false: 不存在
     * @author LewisLouis
     * @createDate 2017-10-17
     */
    private boolean checkHasRoomInBuildOrUnit(String buildId, String unitId) {
        PropertyProjectGetRoomInfoDTO propertyProjectGetRoomInfoDTO = new PropertyProjectGetRoomInfoDTO();
        propertyProjectGetRoomInfoDTO.setBuildId(buildId);
        propertyProjectGetRoomInfoDTO.setUnitId(unitId);
        return null != iPropertyRoomInfoServiceClient.getOneRoomInfo(propertyProjectGetRoomInfoDTO);
    }


}
